<template>
  <div class="space-y-4">
    <!-- 文件选择区域 -->
    <div class="border-2 border-dashed border-background-600 rounded-xl p-6 text-center hover:border-primary-500/50 transition-all duration-normal bg-background-800/50 backdrop-blur-sm">
      <input
        ref="fileInput"
        type="file"
        accept="image/jpeg,image/png,image/webp"
        class="hidden"
        @change="handleFileSelect"
      />
      
      <div v-if="!selectedFile && !previewUrl" @click="triggerFileSelect" class="cursor-pointer group">
        <div class="mx-auto h-16 w-16 text-background-400 group-hover:text-primary-400 transition-colors duration-normal">
          <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-full h-full">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
          </svg>
        </div>
        <div class="mt-4 flex text-sm text-text-secondary group-hover:text-text-primary transition-colors duration-normal justify-center items-center">
          <span class="relative bg-background-800 rounded-lg font-medium text-primary-400 hover:text-primary-300 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-primary-500 px-3 py-1 border border-background-600 hover:border-primary-500/50 transition-all duration-normal">
            选择图片
          </span>
          <p class="pl-2">或拖拽到此处</p>
        </div>
        <p class="text-xs text-text-muted mt-3 group-hover:text-text-secondary transition-colors duration-normal">
          支持 JPG、PNG、WebP 格式，最大 {{ formatFileSize(maxFileSize) }}
        </p>
      </div>

      <!-- 文件预览 -->
      <div v-if="selectedFile || previewUrl" class="space-y-4 animate-fade-in">
        <div class="relative inline-block group">
          <img
            :src="previewUrl || (selectedFile ? createObjectURL(selectedFile) : '')"
            :alt="selectedFile?.name || '预览图片'"
            class="max-h-48 max-w-full rounded-xl object-cover border border-background-600 shadow-lg group-hover:border-primary-500/50 transition-all duration-normal"
          />
          <button
            type="button"
            v-if="selectedFile"
            @click="removeFile"
            class="absolute -top-2 -right-2 bg-error text-white rounded-full w-7 h-7 flex items-center justify-center hover:bg-error/90 transition-all duration-normal shadow-lg hover:scale-110 transform"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <!-- 文件信息 -->
        <div v-if="selectedFile" class="text-sm text-text-secondary space-y-2 bg-background-700/50 rounded-lg p-4 border border-background-600">
          <div class="flex justify-between">
            <span>文件名:</span>
            <span class="font-medium text-text-primary">{{ selectedFile.name }}</span>
          </div>
          <div class="flex justify-between">
            <span>原始大小:</span>
            <span>{{ formatFileSize(selectedFile.size) }}</span>
          </div>
          <div v-if="compressedInfo" class="flex justify-between">
            <span>压缩后大小:</span>
            <span class="text-success">{{ compressedInfo.size }}</span>
          </div>
          <div v-if="compressedInfo?.dimensions" class="flex justify-between">
            <span>尺寸:</span>
            <span>{{ compressedInfo.dimensions.width }} × {{ compressedInfo.dimensions.height }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex space-x-3">
          <button
            type="button"
            @click="triggerFileSelect"
            class="px-4 py-2 border border-background-600 rounded-lg text-sm font-medium text-text-secondary bg-background-800 hover:bg-background-700 hover:text-text-primary hover:border-primary-500/50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-all duration-normal"
          >
            重新选择
          </button>
          <button
            type="button"
            v-if="selectedFile && !compressedInfo"
            @click="previewCompression"
            :disabled="isCompressing"
            class="px-4 py-2 bg-primary-600 border border-transparent rounded-lg text-sm font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-normal shadow-neon"
          >
            {{ isCompressing ? '压缩中...' : '预览压缩' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 错误信息 -->
    <div v-if="error" class="text-error text-sm bg-error/10 border border-error/20 rounded-lg p-4 animate-fade-in">
      {{ error }}
    </div>

    <!-- 上传进度 -->
    <div v-if="isUploading" class="space-y-3 animate-fade-in">
      <div class="flex justify-between text-sm text-text-secondary">
        <span>上传中...</span>
        <span class="text-primary-400 font-medium">{{ uploadProgress }}%</span>
      </div>
      <div class="w-full bg-background-700 rounded-full h-2 overflow-hidden">
        <div
          class="bg-gradient-to-r from-primary-500 to-primary-600 h-2 rounded-full transition-all duration-300 shadow-neon"
          :style="{ width: uploadProgress + '%' }"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useMovieFileUpload } from '../../composables/movies/useMovieFileUpload'

interface Props {
  modelValue?: File | null
  maxFileSize?: number
  showPreview?: boolean
  previewUrl?: string
}

interface Emits {
  (e: 'update:modelValue', value: File | null): void
  (e: 'file-selected', file: File): void
  (e: 'file-removed'): void
  (e: 'upload-complete', url: string): void
  (e: 'upload-error', error: string): void
  (e: 'compression-complete', file: File): void // 新增：压缩完成事件
}

const props = withDefaults(defineProps<Props>(), {
  maxFileSize: 10 * 1024 * 1024, // 10MB
  showPreview: true
})

const emit = defineEmits<Emits>()

// 文件上传相关
const {
  isUploading,
  uploadProgress,
  uploadError,
  validateImageFile,
  getCompressedFileInfo,
  formatFileSize,
  resetUploadState
} = useMovieFileUpload()

// 组件状态
const fileInput = ref<HTMLInputElement>()
const selectedFile = ref<File | null>(null)
const previewUrl = ref<string>('')
const error = ref<string>('')
const isCompressing = ref(false)
const compressedInfo = ref<{ file: File, size: string, dimensions?: { width: number, height: number } } | null>(null)

// 计算属性
const maxFileSize = computed(() => props.maxFileSize)

// 创建对象URL的辅助函数
const createObjectURL = (file: File): string => {
  return URL.createObjectURL(file)
}

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== selectedFile.value) {
    selectedFile.value = newValue || null
    if (newValue) {
      previewCompression()
    }
  }
}, { immediate: true })

// 监听预览URL变化
watch(() => props.previewUrl, (newPreviewUrl) => {
  if (newPreviewUrl) {
    previewUrl.value = newPreviewUrl
  }
}, { immediate: true })

// 监听上传状态变化
watch(uploadError, (newError) => {
  if (newError) {
    error.value = newError
  }
})

// 方法
const triggerFileSelect = () => {
  fileInput.value?.click()
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  try {
    // 验证文件
    validateImageFile(file)
    
    // 设置选中的文件
    selectedFile.value = file
    emit('update:modelValue', file)
    emit('file-selected', file)
    
    // 清除错误
    error.value = ''
    
    // 预览压缩效果
    await previewCompression()
    
  } catch (err) {
    error.value = err instanceof Error ? err.message : '文件选择失败'
    selectedFile.value = null
    emit('update:modelValue', null)
  }
  
  // 清空input值，允许重复选择同一文件
  if (target) {
    target.value = ''
  }
}

const removeFile = () => {
  selectedFile.value = null
  compressedInfo.value = null
  // 恢复外部传入的预览URL，而不是清空
  previewUrl.value = props.previewUrl || ''
  error.value = ''
  resetUploadState()
  emit('update:modelValue', null)
  emit('file-removed')
}

const previewCompression = async () => {
  if (!selectedFile.value) return
  
  try {
    isCompressing.value = true
    compressedInfo.value = await getCompressedFileInfo(selectedFile.value)
    
    // 新增：压缩完成后通知父组件
    if (compressedInfo.value?.file) {
      emit('compression-complete', compressedInfo.value.file)
    }
  } catch (err) {
    console.warn('压缩预览失败:', err)
  } finally {
    isCompressing.value = false
  }
}

// 暴露方法给父组件
const getFile = () => selectedFile.value
const getCompressedFile = () => compressedInfo.value?.file || selectedFile.value
const clearError = () => { error.value = '' }

defineExpose({
  getFile,
  getCompressedFile,
  clearError,
  triggerFileSelect
})
</script> 